package top.truehaku.generator.code.repository.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import top.truehaku.generator.code.domain.model.column.Column;
import top.truehaku.generator.code.domain.model.column.ColumnComment;
import top.truehaku.generator.code.domain.model.column.ColumnId;
import top.truehaku.generator.code.domain.model.column.ColumnType;
import top.truehaku.generator.code.domain.model.table.Table;
import top.truehaku.generator.code.domain.model.table.TableComment;
import top.truehaku.generator.code.domain.model.table.TableId;
import top.truehaku.generator.code.infrastructure.persistence.dao.ColumnDao;
import top.truehaku.generator.code.infrastructure.persistence.dao.TableDao;
import top.truehaku.generator.code.infrastructure.persistence.entity.ColumnDO;
import top.truehaku.generator.code.infrastructure.persistence.entity.TableDO;
import top.truehaku.generator.code.repository.TableRepository;

import java.util.List;
import java.util.stream.Collectors;

@Repository
public class TableRepositoryImpl implements TableRepository {

    @Autowired
    private TableDao tableDao;

    @Autowired
    private ColumnDao columnDao;

    @Override
    public Table findById(TableId tableId) {
        TableDO tableDO = tableDao.selectByTableName(tableId.getTableScheme(), tableId.getTableName());
        List<ColumnDO> columnDOList = columnDao.selectList(tableId.getTableScheme(), tableId.getTableName());
        List<Column> columns = columnDOList.stream().map(column -> new Column(
                new ColumnId(column.getTableSchema(),column.getTableName(),column.getColumnName())
                ,new ColumnType(column.getColumnType())
                ,new ColumnComment(column.getColumnComment())
                ,column.getNullable()
                ,column.getPrimaryKey()
                ,column.getUniqueKey()
                ,column.getAutoIncrement()
                ,column.getOrdinalPosition()
        )).collect(Collectors.toList());

        columns.forEach(column -> {
            if (column.getColumnComment().isCombine()){
                List<String> combineColumns = column.getColumnComment().getCombineColumns();
                List<Column> combines = combineColumns.stream().map(columnStr-> columns.stream().filter(sourceColumn -> sourceColumn.getColumnId().getColumnName().equals(columnStr)).findFirst().get()).collect(Collectors.toList());
                column.setCombineColumns(combines);
            }
        });

        return new Table(new TableId(tableDO.getTableSchema(),tableDO.getTableName())
                ,new TableComment(tableDO.getTableComment())
                ,columns
        );
    }


}
